<?php
/**
 * UserController
 * 
 * Controls the flow of the User UI. 
 */
class UserController
{
	/**
	* Starts to controlling the flow.
	*
	* @return string The html flow.
	*/
	public function doController()
	{
		// Empty container variable.
		$xhtml = '';
		
		require_once 'UserModel.php';
		$userModel = new UserModel();
		
		// Gets an array with all the users.
		$array = $userModel->GetAllUsers();

		require_once 'UserView.php';
		$userView = new UserView();
		
		if( $userView->DeleteUser() )
		{
			// Delete the user with the UserID.
			if( $userModel->DeleteUser( $userView->GetPostUserID() ) )
			{
				// Update the users array.
				$array = $userModel->GetAllUsers();
			}
		}
		
		if( $userView->EditUser() )
		{
			// Get the user from the database.
			$user = $userModel->GetUserById( $userView->GetPostUserID() ) ;
			
			// Får inte med UserID, antagligen för att det blir en POST emellan.
			$xhtml = $userView->doEditUserForm( $user );
		}
		
		// Did the user try to save the edited information?
		if( $userView->Save() )
		{
			// TODO: Validation username, password and email.
			
			// Checks the old password.
			if( $userModel->VerifyPassword( $_POST['EditUserID'], sha1( $_POST['oldPassword']) ) )
			{
				// Passwordmatch.
				if( $userView->newPasswordMatch( $_POST['newPassword'] , $_POST['newPasswordMatch'] ) )
				{
					// Save the changes.
					if( $userModel->SaveChanges( $_POST['EditUserID'], sha1( $_POST['newPassword'] ) , $_POST['email'] ) == FALSE )
					{
						echo "Something went wrong, could not save the changes.";
					}
					
					// Update the users array.
					$array = $userModel->GetAllUsers();
				}	
			}
		}
		// Did user click 'cancel'.
		else if( $userView->Cancel() )
		{
			// Nothing atm.
		}
		
		// Shows the users in a table.
		$xhtml .= $userView->doUserList( $array );
		
		$xhtml .= "<br />----------------------------------------------------------<br />";
		$xhtml .= "test - ". sha1("test") . "<br />";
		$xhtml .= "----------------------------------------------------------<br />";
		
		return $xhtml;
	}
}